package com.smrtcold.dev.init;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.Date;

/**
 * @author : maqiang
 * @classname : AppStartupListener
 * @description : 启动日志打印
 * @date : 2020/12/9 14:29
 */
@Slf4j
@Component
public class AppStartupListener implements ApplicationRunner, Ordered {

    /**
     * 上下文对象实例
     */
    @Resource
    private ApplicationContext ctx;

    @Value("${server.port}")
    private int port;

    String APP_START_INFO =
            "\n"+
                    "==============================================================\n"+
                    "\tApp:\t{}\n"+
                    "\tState:\tapp is running\n"+
                    "\tPID:\t{}\n"+
                    "\tDate:\tstarted at {}\n"+
                    "\tURLs:\thttp://{}:{}{}\n"+
                    "==============================================================";
    /**
     * Callback used to run the bean.
     *
     * @param args incoming application arguments
     * @throws Exception on error
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String appName = ctx.getEnvironment().getProperty("spring.application.name");
        String appJvmName = ManagementFactory.getRuntimeMXBean().getName();
        String appHost = InetAddress.getLocalHost().getHostAddress();
        String appPort = ctx.getEnvironment().getProperty("server.port");
        String appPath = ctx.getEnvironment().getProperty("server.servlet.context-path");
//        String appStartupDate = DateUtil.format(new Date(ctx.getStartupDate()), DatePattern.NORM_DATETIME_MS_PATTERN);
        log.info(APP_START_INFO,appName,appJvmName.split("@")[0]," ",appHost,appPort,(appPath==null?"":appPath));
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

   // @EventListener({ApplicationReadyEvent.class})
    void applicationReadyEvent() {
        // 启动后访问地址
        String url = "http://localhost:"+this.port;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
